using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.ViewModels.Email;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;

namespace CRM.Controllers.Email
{
    /*
     *  https://www.drageasy.com/video.html
     *  https://www.drageasy.com/video/iframe-demo.html
     *  https://www.drageasy.com/api.html
     */
    [Route("api/[controller]")]
    [ApiController]
    public class EmailTemplateController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        public EmailTemplateController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }
        
        [HttpPost(nameof(Index))]
        public async Task<ResultStruct> Index(EmailTemplateListQuery query) 
        {
            var user = await _userManager.GetUserAsync(User);
            var result =
                await _dbContext.EmailTemplate
                    .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                    .WhenWhere(!string.IsNullOrEmpty(query.Title), m => m.Title.StartsWith(query.Title) || m.Title.EndsWith(query.Title))
                    .WhenWhere(query.Type != 0 && query.Type != null, m => m.Type == query.Type)
                    .WhenWhere(query.Attribute != 0 && query.Attribute != null, m => m.Attribute == query.Attribute)
                    .WhenWhere(query.CreatedAt != null && query.CreatedAt.Length == 2, m => m.CreatedAt >= query.CreatedAt[0] && m.CreatedAt <= query.CreatedAt[1].AddDays(1))
                    .OrderByDescending(m => m.Id)
                    .ToPaginateAsync(query.Page, query.Limit);
            return Success(result);
        }
        
        [HttpGet(nameof(SelectTemplateList))]
        public async Task<ResultStruct> SelectTemplateList() 
        {
            var user = await _userManager.GetUserAsync(User);
            var model = _dbContext.EmailTemplate .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id);
            var tep = await model.ToListAsync();
            var templateOptions = tep.Select(m => new
            {
                displayName = m.Title,
                key = m.Id,
                type = m.Type
            });
            return Success(new { templateOptions });
        }
        
        [HttpGet("[action]")]
        public async Task<ResultStruct> GetFieldsById([FromQuery] int id)
        {           
            var user = await _userManager.GetUserAsync(User);
            var result = _dbContext.EmailTemplate
            .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
            .Select(s => new {
                s.Id,
                s.Title,
                s.TemplateContent,
                s.Type,
                s.Attribute
            }).Single(s => s.Id.Equals(id));
            return Success(result);
        } 
        
        [HttpGet(nameof(Delete))]
        public async Task<ResultStruct> Delete([FromQuery] int id) 
        {
            var row = await _dbContext.EmailTemplate.FindAsync(id);
            if (row == null) return Error(message: "无权操作");
            await _dbContext.EmailTemplate.Where(m => m.Id == id).DeleteAsync();
            await _dbContext.SaveChangesAsync();
            return Success();
        }
        
        
        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(EmailTemplateCreateVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var model = vm.NewModel(user);
            await _dbContext.EmailTemplate.AddAsync(model);
            await _dbContext.SaveChangesAsync();
            return Success(new { Id = model.Id });
        }
        
        [HttpPost("[action]")]
        public async Task<ResultStruct> Edit(EmailTemplateCreateVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            // if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var model = 
                await _dbContext.EmailTemplate
                    .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                    .Where(m => m.Id == vm.Id)
                    .FirstAsync();
            vm.EditModel(model);
            await _dbContext.SaveChangesAsync();
            var id = vm.Id;
            var result = new { Id = id };
            return Success(result);
        }
    }
}